package com.nageoffer.aicloud.common.bi.user;

import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.nageoffer.aicloud.common.database.SecurityUserDetails;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * 用户登录过滤器
 */
@Component
public class LoginAuthenticationFilter extends OncePerRequestFilter {
    @Value("${jwt.secret}")
    private String jwtSecret;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("Authorization");
        if (StrUtil.isNotBlank(token)) {
            // 验证 JWT 是否正确性
            if (JWTUtil.verify(token, jwtSecret.getBytes())) {
                JWT jwt = JWTUtil.parseToken(token);
                if (jwt != null && jwt.getPayload("id") != null) {
                    long id = Long.parseLong(jwt.getPayload("id").toString());
                    String username = (String) jwt.getPayload("username");
                    // 将用户信息设置到 security 中
                    SecurityUserDetails userDetails = new SecurityUserDetails(id, username, "");
                    // 认证对象
                    UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails,
                            null, userDetails.getAuthorities());
                    authenticationToken.setDetails(new WebAuthenticationDetailsSource()
                            .buildDetails(request));
                    // 设置了存储列表才有权限否则 403
                    SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                }
            }
        }
        // 继续执行下面的过滤器
        filterChain.doFilter(request, response);
    }
}
